package com.waitingresult.security.config;

import com.waitingresult.security.utils.PasswordUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * All right reserved,Designed By WangShuai
 * <p>
 * SpringSecurity 的配置类
 *
 * @author : WangShuai
 * @version : V1.0
 * @ClassName : SecurityConfig
 * @Description :
 * @date : 2021/9/8 10:22
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*

    @Resource
    @Qualifier("userdetailsService")
    private UserDetailsService userDetailsService;
*/

    // 1. 配置 用户信息服务
    //com.waitingresult.security.service.impl.UserDetailsServiceImpl
/*
    @Bean
    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }
*/

    // 2. 配置 密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordUtils.getEncoder();
    }

    // 3. 配置 安全拦截机制

    //密码检查规则
  /*  @Override
    protected void configure(AuthenticationManagerBuilder managerBuilder) throws Exception {
        managerBuilder.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }
*/
    /**
     * <p>安全拦截机制</p>
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭csrf，要不然访问/login会一直报错提示没有权限
        http.csrf().disable();
        // 开启跨域
        http.cors();
        // Security的会话管理
        //Spring Security 永远不会创建HttpSession并且永远不会使用它来获取SecurityContext
        //TODO 后续使用JWT 需要设置成 不用session 的状态
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        //TODO 权限 后续从Nacos的配置文件中读取.
        http.authorizeRequests()
                .anyRequest().permitAll();//所有的请求, 都可以匿名访问


        // 登出操作.
        //http.logout()

    }
}
